<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 聊天室</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --private-color: #f59e42;
            --system-color: #666;
            --own-message-color: #667eea;
            --other-message-color: #f0f0f0;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: var(--primary-gradient);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 1000px;
            height: 80vh;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            display: flex;
            overflow: hidden;
        }

        /* 左侧用户列表 */
        .user-list {
            width: 220px;
            background: #f8f9fa;
            border-right: 1px solid #e0e0e0;
            padding: 20px 0;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }

        .user-list-header {
            padding: 0 20px 15px;
            border-bottom: 1px solid #e0e0e0;
            margin-bottom: 15px;
        }

        .user-list h3 {
            text-align: center;
            margin-bottom: 10px;
            font-size: 18px;
            color: #333;
        }

        .current-user {
            display: flex;
            align-items: center;
            padding: 10px;
            background: #e0e7ff;
            border-radius: 10px;
            margin-bottom: 15px;
        }

        .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: var(--primary-gradient);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
        }

        .username {
            font-weight: 500;
        }

        .user-list ul {
            list-style: none;
            padding: 0 10px;
            margin: 0;
            flex: 1;
        }

        .user-list li {
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
        }

        .user-list li:hover {
            background: #e0e7ff;
        }

        .user-list li.active {
            background: #d0d7ff;
            font-weight: 500;
        }

        .user-list li i {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #28a745;
            margin-right: 10px;
        }

        /* 主聊天区域 */
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: var(--primary-gradient);
            color: white;
            padding: 15px 25px;
            font-weight: bold;
            font-size: 20px;
        }

        .chat-mode {
            font-size: 14px;
            font-weight: normal;
            opacity: 0.8;
            margin-top: 5px;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 15px;
            display: flex;
            max-width: 80%;
        }

        .message.own {
            margin-left: auto;
            flex-direction: row-reverse;
        }

        .message-content {
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.4;
        }

        .message.own .message-content {
            background: var(--primary-gradient);
            color: white;
            border-bottom-right-radius: 5px;
        }

        .message:not(.own) .message-content {
            background: var(--other-message-color);
            color: #333;
            border-bottom-left-radius: 5px;
        }

        .message-info {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            display: flex;
            justify-content: space-between;
        }

        .message.own .message-info {
            flex-direction: row-reverse;
        }

        .private-label {
            background: var(--private-color);
            color: white;
            font-size: 11px;
            padding: 2px 8px;
            border-radius: 10px;
            margin-left: 8px;
        }

        .system-message {
            text-align: center;
            color: var(--system-color);
            font-style: italic;
            margin: 15px 0;
            font-size: 14px;
        }

        .chat-input {
            padding: 15px 20px;
            background: white;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 12px;
        }

        .chat-input input {
            flex: 1;
            padding: 12px 18px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            outline: none;
            font-size: 16px;
        }

        .chat-input input:focus {
            border-color: #667eea;
        }

        .chat-input button {
            padding: 12px 25px;
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: bold;
            transition: transform 0.2s;
        }

        .chat-input button:hover {
            transform: translateY(-2px);
        }

        .chat-input button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .connection-status {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            border-radius: 20px;
            color: white;
            font-weight: bold;
            z-index: 1000;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
        }

        .connection-status::before {
            content: '';
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-connected {
            background: #28a745;
        }

        .status-connected::before {
            background: #ffffff;
        }

        .status-disconnected {
            background: #dc3545;
        }

        /* 响应式 */
        @media (max-width: 768px) {
            .chat-container {
                flex-direction: column;
                height: 90vh;
            }

            .user-list {
                width: 100%;
                border-right: none;
                border-bottom: 1px solid #e0e0e0;
                height: 150px;
            }

            .chat-header {
                font-size: 18px;
            }
        }

        /* 用户名输入框样式 */
        .username-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
        }

        .username-form {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            width: 90%;
            max-width: 400px;
            text-align: center;
        }

        .username-form h2 {
            margin-bottom: 20px;
            color: #333;
        }

        .username-form input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-size: 16px;
            margin-bottom: 20px;
            outline: none;
        }

        .username-form input:focus {
            border-color: #667eea;
        }

        .username-form button {
            padding: 12px 30px;
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: bold;
            font-size: 16px;
            transition: transform 0.2s;
        }

        .username-form button:hover {
            transform: translateY(-2px);
        }
    </style>
</head>
<body>
<div class="username-modal" id="usernameModal">
    <div class="username-form">
        <h2>欢迎加入聊天室</h2>
        <input type="text" id="usernameInput" placeholder="请输入您的用户名" autofocus>
        <button id="joinChatBtn">加入聊天</button>
    </div>
</div>

<div class="connection-status" id="connectionStatus">连接中...</div>
<div class="chat-container">
    <!-- 左侧用户列表 -->
    <div class="user-list">
        <div class="user-list-header">
            <h3>在线用户</h3>
        </div>
        <div class="current-user">
            <div class="user-avatar" id="currentUserAvatar">?</div>
            <div>
                <div id="currentUsername">未登录</div>
                <small>在线</small>
            </div>
        </div>
        <ul id="userList"></ul>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main">
        <div class="chat-header">
            <div>WebSocket 聊天室</div>
            <div class="chat-mode" id="chatMode">当前：群聊模式</div>
        </div>
        <div class="chat-messages" id="messageArea">
            <div class="system-message">欢迎来到聊天室！请输入用户名开始聊天</div>
        </div>
        <div class="chat-input">
            <input type="text" id="message" placeholder="输入消息..." disabled>
            <button id="send" disabled>发送</button>
        </div>
    </div>
</div>
<script>
    let stompClient = null;
    let username = null;
    let users = [];
    let currentChatUser = 'public'; // 当前聊天对象: 'public'表示群聊，否则为用户名
    let chatHistory = { public: [] }; // 聊天历史记录
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    const reconnectDelay = 3000; // 3秒

    function setConnectionStatus(connected) {
        const status = document.getElementById('connectionStatus');
        status.textContent = connected ? '已连接' : '连接断开，正在重连...';
        status.className = `connection-status ${connected ? 'status-connected' : 'status-disconnected'}`;
    }

    function getAvatarText(name) {
        return name ? name.charAt(0).toUpperCase() : '?';
    }

    function connect() {
        const socket = new SockJS('http://localhost:8080/ws');
        stompClient = Stomp.over(socket);
        stompClient.debug = null;
        const headers = username ? { 'user': username } : {};
        stompClient.connect(
            headers,
            () => onConnected(),
            (error) => onError(error)
        );
    }

    function onConnected() {
        setConnectionStatus(true);
        reconnectAttempts = 0;
        stompClient.subscribe('/topic/public', onPublicMessage);
        stompClient.subscribe('/topic/userlist', onUserListUpdate);
        stompClient.subscribe('/user/queue/private', onPrivateMessage);
        if (username) {
            reJoinChat();
        }
    }

    function joinChat() {
        username = document.getElementById('usernameInput').value.trim();
        if (!username) {
            alert('用户名不能为空');
            return;
        }
        connect();
    }

    function reJoinChat() {
        stompClient.send(
            "/app/chat/addUser",
            {},
            JSON.stringify({ sender: username, type: 'JOIN' })
        );
        document.getElementById('currentUsername').textContent = username;
        document.getElementById('currentUserAvatar').textContent = getAvatarText(username);
    }

    function onError(error) {
        setConnectionStatus(false);
        console.error('连接错误:', error);
        if (reconnectAttempts < maxReconnectAttempts) {
            setTimeout(() => {
                reconnectAttempts++;
                console.log(`尝试重新连接 (${reconnectAttempts}/${maxReconnectAttempts})`);
                connect();
            }, reconnectDelay);
        } else {
            console.error('达到最大重连次数，放弃连接');
        }
    }

    function sendMessage() {
        const input = document.getElementById('message');
        const content = input.value.trim();
        if (content === '') return;
        if (currentChatUser === 'public') {
            stompClient.send(
                "/app/chat/sendMessage",
                {},
                JSON.stringify({
                    sender: username,
                    content: content,
                    type: 'CHAT'
                })
            );
        } else {
            stompClient.send(
                "/app/chat/private",
                {},
                JSON.stringify({
                    sender: username,
                    receiver: currentChatUser,
                    content: content,
                    type: 'PRIVATE'
                })
            );
        }
        input.value = '';
        input.focus();
    }

    function onPublicMessage(payload) {
        console.log('收到群聊消息:', payload.body);
        const message = JSON.parse(payload.body);
        console.log('解析后的消息:', message);
        saveMessage('public', message);
        if (currentChatUser === 'public') {
            renderMessages();
        }
    }

    function onPrivateMessage(payload) {
        console.log('收到私聊消息:', payload.body);
        const message = JSON.parse(payload.body);
        console.log('解析后的私聊消息:', message);
        const chatTarget = message.sender === username ? message.receiver : message.sender;
        saveMessage(chatTarget, message);
        if (currentChatUser === chatTarget) {
            renderMessages();
        }
    }

    function onUserListUpdate(payload) {
        users = JSON.parse(payload.body);
        renderUserList();
        // 自动关闭登录弹窗并更新当前用户显示
        if (users.includes(username)) {
            const modal = document.getElementById('usernameModal');
            if (modal) modal.style.display = 'none';
            document.getElementById('currentUsername').textContent = username;
            document.getElementById('currentUserAvatar').textContent = getAvatarText(username);
            // 启用输入框和发送按钮
            document.getElementById('message').disabled = false;
            document.getElementById('send').disabled = false;
            document.getElementById('message').focus();
        }
    }

    function saveMessage(chatTarget, message) {
        if (!chatHistory[chatTarget]) {
            chatHistory[chatTarget] = [];
        }
        chatHistory[chatTarget].push(message);
    }

    function renderMessages() {
        const container = document.getElementById('messageArea');
        container.innerHTML = '';
        const msgs = chatHistory[currentChatUser] || [];
        if (msgs.length === 0) {
            const welcome = document.createElement('div');
            welcome.className = 'system-message';
            welcome.textContent = currentChatUser === 'public'
                ? '欢迎进入群聊，输入消息开始和大家聊天吧！'
                : `你正在和 ${currentChatUser} 私聊`;
            container.appendChild(welcome);
        } else {
            msgs.forEach(msg => renderMessage(msg));
        }
        container.scrollTop = container.scrollHeight;
    }

    function renderMessage(message) {
        const container = document.getElementById('messageArea');
        const isOwnMessage = message.sender === username;
        const isSystemMessage = message.type === 'SYSTEM' || message.type === 'JOIN' || message.type === 'LEAVE';
        let messageElement;
        
        // 调试信息
        console.log('渲染消息:', message);
        
        if (isSystemMessage) {
            messageElement = document.createElement('div');
            messageElement.className = 'system-message';
            messageElement.textContent = message.content;
        } else {
            messageElement = document.createElement('div');
            messageElement.className = `message ${isOwnMessage ? 'own' : ''}`;
            
            const content = document.createElement('div');
            content.className = 'message-content';
            
            // 确保消息内容正确显示
            const messageContent = message.content || '';
            content.textContent = messageContent;
            
            if (message.type === 'PRIVATE') {
                const label = document.createElement('span');
                label.className = 'private-label';
                label.textContent = '私聊';
                content.appendChild(label);
            }
            
            const info = document.createElement('div');
            info.className = 'message-info';
            
            if (message.type === 'PRIVATE') {
                const participants = isOwnMessage
                    ? `${message.sender} → ${message.receiver}`
                    : `${message.receiver} ← ${message.sender}`;
                info.textContent = `${participants} • ${message.timestamp || ''}`;
            } else {
                info.textContent = `${message.sender || ''} • ${message.timestamp || ''}`;
            }
            
            messageElement.appendChild(content);
            messageElement.appendChild(info);
        }
        container.appendChild(messageElement);
    }

    function renderUserList() {
        const list = document.getElementById('userList');
        list.innerHTML = '';
        // 群聊按钮
        const publicChat = document.createElement('li');
        publicChat.innerHTML = '<i></i> 群聊';
        publicChat.className = currentChatUser === 'public' ? 'active' : '';
        publicChat.addEventListener('click', () => {
            switchChat('public');
        });
        list.appendChild(publicChat);
        // 在线用户
        users.forEach(user => {
            if (user === username) return;
            const item = document.createElement('li');
            item.innerHTML = `<i></i> ${user}`;
            item.className = currentChatUser === user ? 'active' : '';
            item.addEventListener('click', () => {
                switchChat(user);
            });
            list.appendChild(item);
        });
    }

    function switchChat(target) {
        currentChatUser = target;
        document.getElementById('chatMode').textContent =
            `当前：${target === 'public' ? '群聊模式' : `与 ${target} 私聊中`}`;
        renderMessages();
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('joinChatBtn').addEventListener('click', joinChat);
        document.getElementById('usernameInput').addEventListener('keypress', e => {
            if (e.key === 'Enter') joinChat();
        });
        document.getElementById('send').addEventListener('click', sendMessage);
        document.getElementById('message').addEventListener('keypress', e => {
            if (e.key === 'Enter') sendMessage();
        });
    });

    window.addEventListener('beforeunload', () => {
        if (stompClient) {
            stompClient.disconnect();
        }
    });
</script>
</body>
</html>